#include"message.h"
#include"timeStamp.h"
#include"public.h"
#include<sstream>
#include<iostream>
//                                              上什么颜色          上深浅的颜色    上色完成之后分隔符怎样分割          给哪个字段上     要不要上色               
std::string Message::FormatFieldWithColor(COLOR_NUMBER colorNumber,bool dark,const std::string& delimiter,const std::string& fieldName,bool colored)
{
    std::stringstream ss;//格式化字符串
    if(colored){
        ss<<"\033["<<dark<<";"<<colorNumber<<"m";
    }
    ss<<fieldName;
    if(colored)
    {
        ss<<"\033[0m";//重置属性
    }
    ss<<delimiter;//表示分隔符
    return ss.str();
}
Message::Message(LOG_LEVEL level,const std::string& absoluteFileName,const std::string&functionName,int lineNUmber)
{
    std::string fileName=absoluteFileName;
    int pos=0;
    int i=fileName.length()-1;
    for(;i>=0;--i)
    {
        if(fileName[i]=='/')
        {
            pos=i;
            break;
        }
    }
    fileName=fileName.substr(pos+1,fileName.length()-pos);
    m_coloredHeader=FormatHeader(level,fileName,functionName,lineNUmber,true);
    m_commonHeader=FormatHeader(level,fileName,functionName,lineNUmber,false);
}
//                                     [时间戳][日志级别][文件名称][函数名称][行号]
std::string Message::FormatHeader(LOG_LEVEL level, const std::string& fileName,const std::string& functionName, int lineNumber, bool colored) 
{                
    // 时间戳
    std::stringstream ss;
    ss << FormatFieldWithColor(DEFAULT_COLOR, 0, "", TimeStamp::Now().ToString(), colored);

    // 日志级别  INFO -> "[INFO]"
    COLOR_NUMBER logColorNumber = LogLevelColor[level];
    std::string logLevelType = LogLevelTypeString[level];
    ss << FormatFieldWithColor(logColorNumber, 1, "", logLevelType, colored);
     
    
    // 文件名称
    COLOR_NUMBER fileColor = LogFeildColor[FILE_NAME];
    ss << FormatFieldWithColor(fileColor, 1, "", "["+fileName+"]", colored); 
    // 函数名称
    COLOR_NUMBER functionColor = LogFeildColor[FUNCTION_NAME];
    ss << FormatFieldWithColor(functionColor, 1, "", "["+functionName+"]", colored);
    // 行号
    COLOR_NUMBER lineColor = LogFeildColor[LINE];
    ss << FormatFieldWithColor(lineColor, 1, ":", "["+std::to_string(lineNumber)+"]", colored);
    return ss.str();
}

std::string Message::Tostring(bool colored)const
{
    return colored?m_coloredHeader+m_msg:m_commonHeader+m_msg;      
}

// int main()
// {
//     Message msg1(INFO,__FILE__,__FUNCTION__,__LINE__);//[时间戳][/home/ubuntu/test/src/message.cc][main][58]
//     Message msg2(ERROR,__FILE__,__FUNCTION__,__LINE__);
//     Message msg3(DEBUG,__FILE__,__FUNCTION__,__LINE__);
//     Message msg4(FATAL,__FILE__,__FUNCTION__,__LINE__);
//     msg1<<"hello world1";
//     msg2<<"hello world2";
//     msg3<<"hello world3";
//     msg4<<"hello world4";
//     std::cout<<msg1.Tostring()<<std::endl;
//     std::cout<<msg2.Tostring()<<std::endl;
//     std::cout<<msg3.Tostring()<<std::endl;
//     std::cout<<msg4.Tostring()<<std::endl;
//     return 0;
// }